package practice.top145;

public class Solution38 {
    public String countAndSay(int n) {
        StringBuffer sb = new StringBuffer(String.valueOf(1));
        int count = 1;
        int index = 1;
        while (--n > 0) {
            String str = sb.toString();
            sb.delete(0, sb.length());
            while (index < str.length()) {
                if (str.charAt(index) == str.charAt(index - 1)) {
                    count++;
                } else {
                    sb.append(count);
                    count = 1;
                    sb.append(str.charAt(index - 1));
                }
                index++;
            }
            sb.append(count);
            count = 1;
            sb.append(str.charAt(index - 1));
            index = 1;
        }
        return sb.toString();
    }
}
